﻿using System.Diagnostics;
using System.IO.IsolatedStorage;

namespace TakePhotoTogether.Dao
{
    public class IsolatedStorageDao
    {
        private const string DEBUG_TAG = "TakePhotoTogether.Dao.IsolatedStorageDao => ";
        private static IsolatedStorageSettings settings = null;

        private const string version_settings = "version_settings";
        private const int storage_version = 1;

        private static IsolatedStorageSettings GetSettings()
        {
            if (settings == null)
            {
                settings = IsolatedStorageSettings.ApplicationSettings;

                // Verify storage version
                if (!settings.Contains(version_settings) || 
                    ((int)settings[version_settings]) != storage_version)
                {
                    /** Need to update storage **/
                    
                    // Clear
                    settings.Clear();
                    clearAppStorage();

                    // Set new version
                    settings[version_settings] = storage_version;
                    settings.Save();
                    
                }
            }
            return settings;
        }

        public static void Save(object storage, string storageKey)
        {
            Debug.WriteLine(DEBUG_TAG + "saving DAO instance: " + storage);
            
            try
            {
                settings[storageKey] = storage;
                settings.Save();
            }
            catch
            {

            }
        }

        private static void clearAppStorage()
        {
            using (var isolated = IsolatedStorageFile.GetUserStoreForApplication())
            {
                var files = isolated.GetFileNames();
                foreach (var file in files)
                {
                    Debug.WriteLine(DEBUG_TAG + "removing file: " + file);
                    isolated.DeleteFile(file);
                }
                Debug.WriteLine(DEBUG_TAG + "available free space: " + string.Format("{0:N}", (isolated.AvailableFreeSpace / 1024)));
            }
        }

        public static T Load<T>(string storageKey)
        {
            IsolatedStorageSettings s = GetSettings();
            if (!s.Contains(storageKey))
                return default(T);

            return (T)s[storageKey];
        }
    }
}
